package cn.lyh.edu.service.impl;

import cn.lyh.edu.service.dto.MemberQueryCriteria;
import cn.lyh.exception.BadRequestException;
import cn.lyh.edu.domain.EduMember;
import cn.lyh.edu.repository.EduMemberRepository;
import cn.lyh.edu.service.IEduMemberService;
import cn.lyh.utils.PageUtil;
import cn.lyh.utils.QueryHelp;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class EduMemberServiceImpl implements IEduMemberService {
    private final EduMemberRepository eduMemberRepository;


    public EduMemberServiceImpl(EduMemberRepository eduMemberRepository) {
        this.eduMemberRepository = eduMemberRepository;
    }
    /**
     * 获取会员列表数据
     * @param queryCriteria
     * @param pageable
     * @return
     */
    @Override
    public Object getList(MemberQueryCriteria queryCriteria, Pageable pageable) {
        Page<EduMember> page = eduMemberRepository.findAll((root, query, criteriaBuilder)-> QueryHelp.getPredicate(root,queryCriteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page);
    }

    /**
     * 根据ID获取详情信息
     * @param id
     * @return
     */
    @Override
    public EduMember getById(Long id) {
        return eduMemberRepository.findById(id).orElseGet(EduMember::new);
    }



    /**
     * 删除会员信息
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Long id) {
        eduMemberRepository.deleteById(id);
    }

    /**
     * 会员注册
     * @param eduMember
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(EduMember eduMember) {
        // 判断该手机号是否已经注册
        EduMember dbEduMember = eduMemberRepository.findByPhone(eduMember.getPhone());
        if(dbEduMember!=null){
            throw new BadRequestException("注册失败，该手机号已经注册过了");
        }else {
            // 初始化数据
            eduMember.setStatus(1);
            eduMember.setLoginTimes(0);
            eduMemberRepository.save(eduMember);
        }
    }

    /**
     * 会员登录
     * @param eduMember
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public EduMember login(EduMember eduMember) {
        // 根据会员手机号查询会员信息
        EduMember dbEduMember = eduMemberRepository.findByPhone(eduMember.getPhone());
        if(dbEduMember==null){
            throw new BadRequestException("登录失败，手机号："+eduMember.getPhone()+"未注册");
        }else if(!dbEduMember.getPassword().equals(eduMember.getPassword())){
            throw new BadRequestException("登录失败，输入密码不正确！");
        }else {
            // 更新登录次数
            dbEduMember.setLoginTimes(dbEduMember.getLoginTimes()+1);
            eduMemberRepository.save(dbEduMember);
        }
        return dbEduMember;
    }
}